import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
const app = getApp();
Page({
  data: {
    defaultData: {
      title: "收货地址", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    addressList: [],
    pageNum: 0,
    pageSize: 10,
    firstname: "", //名字的第一个文字或字母
    isEmpty: false,
    radio: '1',
    selectAddress: "", 
    fromPage:null,
  },
  onLoad(options) {
    
    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      });
      console.log("options.fromPage",this.data.fromPage);
    }
    // if (selectedAddressId) {
    //   this.setData({
    //     radio: wx.getStorageSync('selectedAddressId')
    //   });
    //   wx.removeStorageSync('selectedAddressId'); // 清除缓存
    // }
  },

  onShow(){
    this.getAddress()
    console.log("dfgdg");
  },

  //收货地址列表
  async getAddress() {
    const that = this
    try {
      const res = await request({
        url: indexApi.addressApi(),
        data: {
          pageNum: this.data.pageNum,
          pageSize: this.data.pageSize
        }
      });
      // 检查数组是否为空并设置isEmpty
      if (res.data.length == 0) {
        console.log("为空");
        this.setData({
          isEmpty: false
        });
      } else {
        this.setData({
          isEmpty: true
        });
      }
      const addressList = res.data.map(item => ({
        ...item,
      }));
      // 找到最后一个 is_default: 0 的地址
      const lastDefaultIndex = addressList.map(item => item.is_default).lastIndexOf(0);
      if (lastDefaultIndex !== -1) {
        // 标记最后一个 is_default: 0 的地址
        addressList[lastDefaultIndex].isLastDefault = true;

        // 将最后一个 is_default: 0 的地址移动到列表顶部
        const lastDefaultItem = addressList.splice(lastDefaultIndex, 1)[0];
        addressList.unshift(lastDefaultItem);
      }
      this.setData({
        addressList: addressList
      })
      console.log("res", res);
      console.log("addressList", that.data.addressList);
    } catch (error) {
      console.error("Error:", error);
    }
  },

  //选择地址
  onChange(event) {
    const selectAddress = event.currentTarget.dataset.address
    this.setData({
      radio: event.detail,
      selectAddress: selectAddress
    });
    console.log("selectAddress", this.data.selectAddress);
  },

  //删除地址
  async deleteAddress(addressId) {
    const addressEntity = {
      addressId
    };
    console.log("addressId", addressId);
    try {
      const res = await request({
        url: indexApi.delAddressApi(),
        method: "POST",
        data: addressEntity
      });
      if (res.code == 200) {
        wx.showToast({
          title: "删除成功",
          icon: "none",
        });
      }
      console.log(res);
      const updatedAddressList = this.data.addressList.filter(item => item.addressId !== addressId);
      console.log("updatedAddressList",updatedAddressList);
      this.setData({
        addressList: updatedAddressList,
      });
      if (this.data.addressList.length === 0) {
        this.setData({
          isEmpty: false
        })
      }
      console.log("Updated addressList:=============", this.data.addressList);
      console.log("isEmpty==================:", this.data.isEmpty);

    } catch (error) {
      console.error("Error:", error);
    }
  },


  //点击删除按钮
  async onClose(event) {
    const {
      position,
      instance
    } = event.detail;
    console.log("event.currentTarget.dataset.addressid", event.currentTarget.dataset);
    const addressId = event.currentTarget.dataset.addressid;
    if (position === 'right') {
      wx.showModal({
        title: '删除确认',
        content: '确认删除该地址吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteAddress(addressId).then(() => {
              instance.close(); // 确保在删除成功后关闭 swipe-cell
            }).catch(() => {
              instance.close();
            });
          } else {
            instance.close();
          }
        }
      });
    }
  },

  //修改地址
  changeAddress(event) {
    console.log("event.currentTarget.dataset.addressid", event.currentTarget.dataset.address);
    const address = event.currentTarget.dataset.address;
    wx.navigateTo({
      url: `/packageUserCenter/pages/addAddress/index?address=${encodeURIComponent(JSON.stringify(address))}`,
    })
  },

  //确认
  beSure() {
    if (this.data.fromPage == 1) {
      if (Object.keys(this.data.selectAddress).length === 0) {
        wx.showToast({
          title: "请选择一个地址",
          icon: "none",
        });
        return;
      }
      app.globalData.selectedAddress = this.data.selectAddress;
      console.log("app.globalData.selectedAddress", app.globalData.selectedAddress);
      wx.navigateBack()
      console.log("====================");
      // wx.navigateTo({
      //   url: '/packageOrder/pages/houseType/index',
      // })
    } 
    else {
      wx.navigateBack()
    } 
  },

  //添加地址
  toAddAddress() {
    wx.navigateTo({
      url: '/packageUserCenter/pages/addAddress/index?fromPage=2',
    })
  },
  toBack() {
    wx.navigateBack({
      delta: 1
    });
  }
})